package com.zhongxi.guoyuan.view.coinShopping;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.BaiduNaviManager.NaviInitListener;
import com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanListener;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.BannerAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.coinStore.CoinShopDetailData;
import com.zhongxi.guoyuan.entity.coinStore.GoodsDetailData;
import com.zhongxi.guoyuan.entity.coinStore.GoodsDetailResult;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.widget.ViewFlow;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CoinGoodsActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvAddCheckstand;
    private TextView tvGoHere;
    private PopupWindow popupWindow;
    private LinearLayout relaBottom;
    private View popupWindow_view;
    private View line;
    private TextView tvName;
    private String id;

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default :
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };

    //地图导航
    private static final String APP_FOLDER_NAME = "Meirongyuan";
    private String mSDCardPath = null;
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    public static List<Activity> activityList = new LinkedList<Activity>();
//    private ImageView ivImg;
    private TextView tvView;
    private TextView tvCoin;
    private TextView tvOriginPrice;
    private TextView tvCollect;
    private String type;
    private Map<String, String> map = new HashMap<String, String>();
    private TextView tvShare;
    private TextView tvImgDes;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;
    private GoodsDetailResult result;
    private View popupWindowview;
    private PopupWindow popWindow;
    private WebView webView;
    private ViewFlow mViewFlow;
    private BannerAdapter mBannerAdapter;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_coin_goods);
        initTitle();
        id = getIntent().getStringExtra("goodsId");
        mShareAPI = UMShareAPI.get(this);
        tvTitle.setText("银币商家产品详情");
        tvGoHere = (TextView) findViewById(R.id.tvGoHere);
        tvName = (TextView) findViewById(R.id.tvName);
        tvImgDes = (TextView) findViewById(R.id.tvImgDes);
        line = (View) findViewById(R.id.line);
        tvAddCheckstand = (TextView) findViewById(R.id.tvAddCheckstand);
        relaBottom = (LinearLayout) findViewById(R.id.relaBottom);

        tvView = (TextView) findViewById(R.id.tvView);
        tvCoin = (TextView) findViewById(R.id.tvCoin);
        tvOriginPrice = (TextView) findViewById(R.id.tvOriginPrice);
        webView = (WebView) findViewById(R.id.webView);
        tvCollect = (TextView) findViewById(R.id.tvCollect);
        tvShare = (TextView) findViewById(R.id.tvShare);

//        mapNavi();//初始化百度导航
        initWebView();

    }

    private void mapNavi() {
        activityList.add(this);
        if (initDirs()) {
            initNavi();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        type = "goodsdetail";
        String str = "&gid="+id;
        getServer(Url.GOODS_DETAILS, null, str, false, null, "get");
    }

    /**
     * 轮播
     * @param images
     */
    private void lunbo(List<String> images) {
        //初始化轮播控件
        mViewFlow = (ViewFlow) findViewById(R.id.viewflow);

        if(images.size()>0)
            mViewFlow.setSideBuffer(images.size()); // 实际图片数量
        if(mBannerAdapter == null){
            mBannerAdapter = new BannerAdapter(this, images);
            mViewFlow.setAdapter(mBannerAdapter);
        }else{
            mBannerAdapter.replaceAll(images);
        }
        mViewFlow.startAutoFlowTimer();
    }

    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setBlockNetworkImage(false);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            webView.getSettings().setMixedContentMode(webView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }
    }

    private String getNewContent(String htmltext){
        Document doc= Jsoup.parse(htmltext);
        Elements elements=doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width","100%").attr("height","auto");
        }
        return doc.toString();
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("goodsdetail".equals(type)){
                result = gson.fromJson(response, GoodsDetailResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                initGoodsData(result);
            }else if("collection".equals(type)){
                BaseResponse res = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(res.getSafeobj());
                showShortToast("收藏成功！");
            }else if("shareget".equals(type)){
                ShareBeautifulResult result = gson.fromJson(response, ShareBeautifulResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showPopupWindow(result.getNum());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void showPopupWindow(String num) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvTips.setText("成功分享获得"+num+"个美币");
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse res = gson.fromJson(response, BaseResponse.class);
        if(null!=res.getSafeobj()&&!"".equals(res.getSafeobj()))
        MyApplication.getInstance().setSpValue(res.getSafeobj());
        if(6206==res.getCode()){
            showShortToast("该项目已经收藏");
        }else if(1001==res.getCode()){
            showShortToast("用户未登录，请先登录");
        }else if(1000==res.getCode()){
            showShortToast("项目已下架");
            finish();
        }
    }

    /**
     * 添加商品数据
     * @param result
     */
    private void initGoodsData(GoodsDetailResult result) {
        if(null!=result.getGoodsInfo()&&!"".equals(result.getGoodsInfo())){
            GoodsDetailData goodsInfo = result.getGoodsInfo();
            if(null!=goodsInfo.getImages()&&goodsInfo.getImages().size()>0){
                lunbo(goodsInfo.getImages());
            }
            if(null!=goodsInfo.getSubject()&&!"".equals(goodsInfo.getSubject())){
                tvImgDes.setText(goodsInfo.getSubject());
            }else{
                tvImgDes.setText("");
            }
            if(null!=goodsInfo.getName()&&!"".equals(goodsInfo.getName())){
                tvName.setText(goodsInfo.getName());
            }else{
                tvName.setText("");
            }
            if(null!=goodsInfo.getViewnum()&&!"".equals(goodsInfo.getViewnum())){
                tvView.setText(goodsInfo.getViewnum());
            }else{
                tvView.setText("");
            }
            if(null!=goodsInfo.getPrice()&&!"".equals(goodsInfo.getPrice())){
                tvCoin.setText(goodsInfo.getPrice());
            }else{
                tvCoin.setText("");
            }
            if(null!=goodsInfo.getMarketprice()&&!"".equals(goodsInfo.getMarketprice())){
                tvOriginPrice.setText("原价："+goodsInfo.getMarketprice());
                tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }else{
                tvOriginPrice.setText("原价：");
                tvOriginPrice.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }
            if(null!=goodsInfo.getDesc()&&!"".equals(goodsInfo.getDesc())){
                webView.loadDataWithBaseURL(null, getNewContent(goodsInfo.getDesc()), "text/html", "utf-8", null);
            }
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvAddCheckstand.setOnClickListener(this);
        tvGoHere.setOnClickListener(this);
        tvCollect.setOnClickListener(this);
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvGoHere:
                getPopupWindow();
                break;
            case R.id.tvAddCheckstand:
                Intent intent = new Intent(context, CoinShoppingDetailActivity.class);
                intent.putExtra("shopid", result.getShopInfo().getId());
                startActivity(intent);
                break;
            case R.id.tvCollect:
                getCollection();
                break;
        }
    }

    private void initPopuWindow() {
        {
            popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
            popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
            popupWindow.setFocusable(true);
            popupWindow.showAtLocation(tvShare, Gravity.BOTTOM, 0, 0);
            TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
            LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
            LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
            LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
            LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
            View.OnClickListener shareClickListener = new View.OnClickListener(){

                @Override
                public void onClick(View v) {
                    switch (v.getId()){
                        case R.id.ll_qq:
                            platform = SHARE_MEDIA.QQ;
                            break;
                        case R.id.ll_wechat:
                            platform = SHARE_MEDIA.WEIXIN;
                            break;
                        case R.id.ll_qzone:
                            platform = SHARE_MEDIA.QZONE;
                            break;
                        case R.id.ll_friendscircle:
                            platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                            break;
                    }
                    new ShareAction(CoinGoodsActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("这个商品不用现金，银币也能结账哦！")
                            .withText("推荐一个好商品："+result.getShopInfo().getName()+"，消费后银币就可结账哦！").withTargetUrl(Url.BASE_URL+"/share/silver/goodsdetails?gid="+id)
                            .share();
                    popupWindow.dismiss();
                }
            };
            ll_qq.setOnClickListener(shareClickListener);
            ll_wechat.setOnClickListener(shareClickListener);
            ll_qzone.setOnClickListener(shareClickListener);
            ll_friendscircle.setOnClickListener(shareClickListener);
            tv_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
        }
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
        }

        @Override




        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
        }

    };

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
            type = "shareget";
            getServer(Url.SHARE, null, "", false, null, "get");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showShortToast("分享取消了");
        }
    };

    private void getCollection() {
        if(!MyTextUtils.isFastDoubleClick()){
            type = "collection";
            map.clear();
            map.put("ftype","3");
            map.put("refid", id);
            getServer(Url.ADD_FAVORITE, map, "", false, null, "post");
        }
    }

    private void getPopupWindow() {
        if (null != popWindow && popWindow.isShowing()) {
            popWindow.dismiss();
            return;
        } else {
            mapNavi();//初始化百度导航
            initPopupWindow();
        }
    }

    private void initPopupWindow() {
        popupWindowview = getLayoutInflater().inflate(R.layout.base_store_detailinfo, null);
        popWindow = new PopupWindow(popupWindowview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setBackgroundDrawable(new ColorDrawable(0));

        popupWindowview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupHeight = popupWindowview.getMeasuredHeight();

        int[] location = new int[2];
        relaBottom.getLocationOnScreen(location);
        popWindow.showAtLocation(relaBottom, Gravity.NO_GRAVITY, location[0], location[1] - popupHeight);

        popupWindowview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(popWindow!=null&&popWindow.isShowing()){
                    popWindow.dismiss();
                    popWindow = null;
                }
                return false;
            }
        });

        ImageView ivCall = (ImageView) popupWindowview.findViewById(R.id.ivCall);
        ImageView ivMapNavi = (ImageView) popupWindowview.findViewById(R.id.ivMapNavi);
        TextView tvPhone = (TextView) popupWindowview.findViewById(R.id.tvPhone);
        TextView tvPosition = (TextView) popupWindowview.findViewById(R.id.tvPosition);
        TextView tvRailWay = (TextView) popupWindowview.findViewById(R.id.tvRailWay);
        TextView tvBus = (TextView) popupWindowview.findViewById(R.id.tvBus);

        if(null!=result.getShopInfo()&&!"".equals(result.getShopInfo())){
            CoinShopDetailData shopinfo = result.getShopInfo();
            if(null!=shopinfo.getPhone()&&!"".equals(shopinfo.getPhone())){
                tvPhone.setText(shopinfo.getPhone());
            }else{
                tvPhone.setText("");
            }
            if(null!=shopinfo.getAddress()&&!"".equals(shopinfo.getAddress())){
                tvPosition.setText(shopinfo.getAddress());
            }else{
                tvPosition.setText("");
            }
            if(null!=shopinfo.getTraffic()&&!"".equals(shopinfo.getTraffic())){
                tvRailWay.setText(shopinfo.getTraffic());
                tvBus.setText(shopinfo.getTraffic());
            }else{
                tvRailWay.setText("");
                tvBus.setText("");
            }
        }

        ivCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拨打电话
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + result.getShopInfo().getPhone());
                intent.setData(data);
                startActivity(intent);
            }
        });

        ivMapNavi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(BaiduNaviManager.isNaviInited()){
                    routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                }
            }
        });

    }

    String authinfo = null;

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                CoinGoodsActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        },  null, ttsHandler, ttsPlayStateListener);

    }

    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            /*case GCJ02: {
                sNode = new BNRoutePlanNode(116.30142, 40.05087, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", null, coType);
                break;
            }
            case WGS84: {
                sNode = new BNRoutePlanNode(116.300821, 40.050969, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(116.397491, 39.908749, "北京天安门", null, coType);
                break;
            }
            case BD09_MC: {
                sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null, coType);
                break;
            }*/
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "百度大厦", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(result.getShopInfo().getLongitude()), Double.parseDouble(result.getShopInfo().getDimensions()), "北京天安门", null, coType);
                break;
            }
            default:
                ;
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
			/*
			 * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "3");
            startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void initSetting(){
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
    }

    /**
     * 获取目录
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
